/**
 * 
 */
package com.befeast.bflatfactory;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.api.xmpp.JID;
import com.google.appengine.api.xmpp.Message;
import com.google.appengine.api.xmpp.MessageBuilder;
import com.google.appengine.api.xmpp.SendResponse;
import com.google.appengine.api.xmpp.XMPPService;
import com.google.appengine.api.xmpp.XMPPServiceFactory;

/**
 * @author oleg
 * 
 */
@SuppressWarnings("serial")
public class GreetMeServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		
		JID jid = null;
		if (user != null) {
			jid = new JID(user.getEmail());
		} else {
			jid = new JID("oleg.kossoy@gmail.com");
		}
		
		String msgBody = "Someone has sent you a gift on Example.com. To view: http://example.com/gifts/";
		Message msg = new MessageBuilder().withRecipientJids(jid).withBody(
				msgBody).build();

		boolean messageSent = false;
		XMPPService xmpp = XMPPServiceFactory.getXMPPService();
		if (xmpp.getPresence(jid).isAvailable()) {
			SendResponse status = xmpp.sendMessage(msg);
			messageSent = (status.getStatusMap().get(jid) == SendResponse.Status.SUCCESS);
		}
		
		resp.setContentType("text/plain");
		
		if (!messageSent) {
			resp.getWriter().println("oops");
		} else {
			resp.getWriter().println("Sent");
		}
	}
}
